import React, {useEffect, useState} from 'react';
import {Button, Form, Input, Modal, Table, TableProps} from 'antd';
import type {JobDescription} from "@/types/resp/jobDescription";
import jobDescriptionApi from '@/api/jobDescriptionApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import EnterpriseSelector from "@/pages/enterprise/EnterpriseSelector.tsx";
import DepartmentSelector from "@/pages/department/DepartmentSelector.tsx";


interface JobDescriptionSelectorProps {
  visible: boolean;
  onJobDescriptionSelected: (selectedJobDescription: { jobDescriptionId?: number; jobDescriptionName?: string; }) => void;
  onCloseJobDescriptionSelector: () => void;
}

const JobDescriptionSelector: React.FC<JobDescriptionSelectorProps> = ({visible, onJobDescriptionSelected, onCloseJobDescriptionSelector}) => {

  const [jobDescriptionSelectorForm] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    jobDescriptionSelectorForm.resetFields();
  };

  const [data, setData] = useState<JobDescription[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<JobDescription>> = await jobDescriptionApi.find(jobDescriptionSelectorForm.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<JobDescription> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<JobDescription>['columns'] = [
    {title: '企业名称', dataIndex: 'enterpriseName', key: 'enterpriseName', width: 100},
    {title: '岗位名称', dataIndex: 'jobTitle', key: 'jobTitle', width: 120},
    {title: '部门名称', dataIndex: 'departmentName', key: 'departmentName', width: 100},
    {title: '工作地点', dataIndex: 'workLocation', key: 'workLocation', width: 80},
    {title: '岗位类型', key: 'jobType', width: 80, render: (_, record) => (
        <span>
        {(function () {
          if (record.jobType === 10) return '全职';
          else if (record.jobType === 20) return '兼职';
          else if (record.jobType === 30) return '实习';
          else return '未知';
        })()}
      </span>
      ),
    },
    {title: '岗位职责', dataIndex: 'responsibilities', key: 'responsibilities', width: 200, ellipsis: true},
    {title: '岗位要求', dataIndex: 'requirement', key: 'requirement', width: 200, ellipsis: true},
    {title: '薪资范围', key: 'salaryRange', width: 120, render: (_, record) => (
        <span>
        {(function () {
          if (record.salaryRange === 1) return '3000~5000';
          else if (record.salaryRange === 2) return '5001~10000';
          else if (record.salaryRange === 3) return '10001~20000';
          else if (record.salaryRange === 4) return '20001~30000';
          else if (record.salaryRange === 5) return '30000以上';
          else return '未知';
        })()}
      </span>
      ),
    },
    {title: '发布日期', key: 'postingDate', width: 120, render: (_, record) => (
      <div>{record.postingDate ? record.postingDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '截止日期', key: 'closingDate', width: 120, render: (_, record) => (
      <div>{record.closingDate ? record.closingDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '招聘人数', dataIndex: 'headCount', key: 'headCount', width: 80},
    {title: '状态', key: 'status', width: 80, render: (_, record) => (
        <span>
        {(function () {
          if (record.status === 10) return '开放';
          else if (record.status === 20) return '关闭';
          else return '未知';
        })()}
      </span>
      ),
    }
  ];

  const handleRowDoubleClick = (row: JobDescription) => {
    onJobDescriptionSelected({
      jobDescriptionId: row.id,
      jobDescriptionName: row.jobTitle,
    })
  };

  const selectorFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onCloseJobDescriptionSelector}>关闭</Button>
    </div>
  );

  useEffect(() => {
    if (visible) {
      onSearch();
    }
  }, [visible]);

  const [enterpriseSelectorVisible, setEnterpriseSelectorVisible] = useState(false);
  const findEnterprise = () => {
    setEnterpriseSelectorVisible(true);
  }
  const handleEnterpriseSelected = (selectedEnterprise: { enterpriseId?: number; enterpriseName?: string; }) => {
    setEnterpriseSelectorVisible(false)
    if (selectedEnterprise && 'enterpriseId' in selectedEnterprise) {
      jobDescriptionSelectorForm.setFieldsValue(Object.assign(jobDescriptionSelectorForm.getFieldsValue(), {
      enterpriseId: selectedEnterprise['enterpriseId'],
      enterpriseName: selectedEnterprise['enterpriseName'],
      }));
    }
  };
  const handleCloseEnterpriseSelector = () => {
    setEnterpriseSelectorVisible(false)
  };
  const [departmentSelectorVisible, setDepartmentSelectorVisible] = useState(false);
  const findDepartment = () => {
    setDepartmentSelectorVisible(true);
  }
  const handleDepartmentSelected = (selectedDepartment: { departmentId?: number; departmentName?: string; }) => {
    setDepartmentSelectorVisible(false)
    if (selectedDepartment && 'departmentId' in selectedDepartment) {
      jobDescriptionSelectorForm.setFieldsValue(Object.assign(jobDescriptionSelectorForm.getFieldsValue(), {
      departmentId: selectedDepartment['departmentId'],
      departmentName: selectedDepartment['departmentName'],
      }));
    }
  };
  const handleCloseDepartmentSelector = () => {
    setDepartmentSelectorVisible(false)
  };

  return (
    <Modal title={"招聘岗位选择器(双击行选中)"} open={visible} onCancel={onCloseJobDescriptionSelector}
        width={'var(--modal-width)'} footer={selectorFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      <Form form={jobDescriptionSelectorForm} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="enterpriseName" label="企业名称">
          <Input.Search placeholder="请选择企业名称" onSearch={findEnterprise} readOnly={true} />
        </Form.Item>
        <Form.Item name="jobTitle" label="岗位名称">
          <Input maxLength={255} placeholder="请输入岗位名称"/>
        </Form.Item>
        <Form.Item name="departmentName" label="部门名称">
          <Input.Search placeholder="请选择部门名称" onSearch={findDepartment} readOnly={true} />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
      </Form>
      <Table<JobDescription> columns={columns} dataSource={data} size="small" rowKey={record => record.id}
                         pagination={{ position: ["bottomCenter"] }} scroll={{ x: 'true' }}
                         onRow={(row) => ({
                           onDoubleClick: (event) => {
                             event.preventDefault();
                             handleRowDoubleClick(row);
                           },
                         })}/>
      <EnterpriseSelector visible={enterpriseSelectorVisible} onEnterpriseSelected={handleEnterpriseSelected} onCloseEnterpriseSelector={handleCloseEnterpriseSelector} />
      <DepartmentSelector visible={departmentSelectorVisible} onDepartmentSelected={handleDepartmentSelected} onCloseDepartmentSelector={handleCloseDepartmentSelector} />
    </Modal>
  );
};

export default JobDescriptionSelector;
